import re

from rest_framework import serializers
from django.contrib.auth.hashers import make_password, check_password

from user.models import User,Area,Address,GoodsCategory,CartModel,SKU,GoodsSpecification,SpecificationOption,SKUSpecification
from utils.errors import PasswordNotEqual,LoginError


class UserAccountBaseSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=32, required=True)
    password = serializers.CharField(required=True, max_length=256)

    class Meta:
        model = User
        fields = '__all__'


class UserEmailSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)

    def validate(self, attrs):
        email = attrs['email']
        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError(detail="邮箱已存在", code=5003)
        email_rexp = "^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$"
        if not re.match(email_rexp,email):
            raise serializers.ValidationError(detail="输入邮箱有误", code=5004)
        return attrs

    class Meta:
        model = User
        fields = '__all__'

class UserLoginSerializer(UserAccountBaseSerializer):
    def validate(self, attrs):
        origin_password = attrs['password']
        username = attrs['username']
        user = User.objects.filter(username=username).first()
        if not user:
            raise serializers.ValidationError(detail="账号或密码不正确", code=5002)
        else:
            password = user.password
            if not check_password(origin_password, password):
                raise serializers.ValidationError(detail="账号或密码不正确", code=5002)
            return attrs

class UserRegisterSerializer(UserAccountBaseSerializer):
    password2 = serializers.CharField(required=True, max_length=256)
    mobile = serializers.CharField(required=True, max_length=11)

    def validate(self, attrs):
       if User.objects.filter(username=attrs['username']).exists():
            raise serializers.ValidationError(detail="用户名以存在", code=6002)
       if User.objects.filter(mobile=attrs['mobile']).exists():
           raise serializers.ValidationError(detail="用户名以存在", code=6003)
       if not attrs['password'] == attrs['password2']:
           raise serializers.ValidationError(detail='两次输入密码不匹配', code=6001)
       return attrs

    def create(self, validated_data):
        password = make_password(validated_data['password'])
        return User.objects.create(username=validated_data['username'], password=password,
                                   mobile=validated_data['mobile'])


class UserSerialiazer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = "__all__"


class AddressSerializer(serializers.ModelSerializer):
    province = AreaSerializer()
    city = AreaSerializer()
    district = AreaSerializer()
    class Meta:
        model = Address
        fields = '__all__'


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'

class CartSkuSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['name', "default_image_url", 'id', 'price',]


class CartSerializer(serializers.ModelSerializer):
    sku = CartSkuSerializer()  # 根据sku的id拿到对象

    class Meta:
        model = CartModel
        fields = ['user', 'c_num', 'is_select', 'sku','is_select']


class CartOrderSkuSerializer(serializers.ModelSerializer):
    sku = CartSkuSerializer()

    class Meta:
        model = CartModel
        fields = ['id', 'c_num', 'sku']

    def to_representation(self, instance):
        serial = super().to_representation(instance)
        amount = instance.c_num * instance.sku.price
        serial['amount'] = amount
        return serial


class GoodsSpecificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsSpecification
        fields = ['name',]


class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ['value',]


class SKUDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ''


class SkuSpecificationSerializer(serializers.ModelSerializer):
    spec = GoodsSpecificationSerializer()
    option = SpecificationOptionSerializer()
    sku = SKUDetailSerializer()

    class Meta:
        model = SKUSpecification
        fields = ['spec', 'option', 'sku']